import {DECIMAL_GOOD_INDEX} from '../../config/index.js'
const utils =  require( '../../utils/util.js');

var app = getApp();

Component({
  options: {
    addGlobalClass: true,
  },

  properties: {
    id: {
      type: String,
      value: '',
    },
    data: {
      type: Object,
      observer(data) {
        if (!data) {
          return;
        }
        let isValidityLinePrice = true;
        if (data.originPrice && data.price && data.originPrice < data.price) {
          isValidityLinePrice = false;
        }
        this.setData({
          goods: data,
          isValidityLinePrice
        });
      },
    },
    currency: {
      type: String,
      value: '¥',
    },
    quantity: {
      type: Number,
      value: 0,
      observe(quantity){
        console.log('quantity数量Observer')
      },
    },
    index: {
      type: Number,
      value: 0
    },

    thresholds: {
      type: Array,
      value: [],
      // observer(thresholds) {
      //   if (thresholds && thresholds.length) {
      //     this.createIntersectionObserverHandle();
      //   } else {
      //     this.clearIntersectionObserverHandle();
      //   }
    //   // },
    },
    globalData:{
      type: Object,
      value: null
    }
  },

  observers:{
    // 'globalData.order.unpay.postType': function(e){
    //   console.log('就餐方式改变 Observers', e)
    //   this.setData({
    //     globalData: this.data.globalData
    //   })
    // },
    'goods.count': function(v){
      if(v){
        this.setData({
          kgTag: 'kg'
        })
      }else{
        this.setData({
          kgTag: ''
        })
      }
    },
    'shops.shopsDetials': function(e){
      console.log('店铺信息改变', e)
    }
  },

  data: {
    imgRootUrl: null,
    independentID: '',
    goods: {
      id: ''
    },
    isValidityLinePrice: false,
    valueError: false,
    goodItem: '',
    DECIMAL_GOOD_INDEX: DECIMAL_GOOD_INDEX,
    dynamicBackgroundColor: 'transparent',
    selectionStart: 0,
    selectionEnd: 0,
    kgTag: '',
    focusOnDecimalInputComponent: false,
    shops: null
  },

  lifetimes: {
    ready() {
      this.init();
      this.setData({
        'goodItem': app.data.globalData.allGoodsList[this.properties.index],
        shops: app.data.shops
      })
      
      console.log("看看是否同一对象2", app.data.shops, app.data.shops.shopsDetails == this.data.shops.shopsDetails)
    },
    detached() {
      this.clear();
    },
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () { 
      // this.setData({
      //   'goodItem': app.data.globalData.allGoodsList[this.properties.index],
      //   shops: app.data.shops
      // })
      
      // console.log("看看是否同一对象2", app.data.shops, app.data.shops.shopsDetails == this.data.shops.shopsDetails)
    },
    hide: function () { },
    resize: function () { },
  },

  methods: {
    _triggleRefreshGoodCount(v){
      // 向上发事件，修改unpay数组
      this.triggerEvent('refresh-cart', {
        quantity: v,
        goods: this.data.goods,
      });
    },

    onQuantityInput(e) {
      var value = e.detail.value.replace(/[^0-9]/g, '');
      value = value.replace(/^0+/, ''); // 删除开头的所有 0

      // 3. 如果值为空，设置为 0（可选）
      if (value === '') {
        value = 0;
      }
      this.setData({
        'goods.count': value,
      })
      this._triggleRefreshGoodCount(value);
    },

    onFocusHandler(e){
      const value = e.detail.value;
      const length = value.length;

      this.setData({
        dynamicBackgroundColor: 'whitesmoke',
        selectionStart: 0,
        selectionEnd: length
      }, ()=>{
        console.log(this.data.selectionStart, this.data.selectionEnd)
      })
    },
    onBlurHandler(e){
      this.setData({
        dynamicBackgroundColor: 'transparent'
      })
    },

    onQuantityInputBlur(e){
      console.log('input blur失去焦点')
      if(this.properties.goods.count == 0){
        this.setData({
          'goods.count': ''
        })
      }
      this.setData({
        dynamicBackgroundColor: 'transparent',
        focusOnDecimalInputComponent: false
      })

    },

    onQuantityInputDecimal(e){
      var value = e.detail.value;
      var {valueText, value} = utils.decimalInputRegular(value, 3);

      this.setData({
        'goods.count': value,
      })
      this._triggleRefreshGoodCount(value);
    },

    handlePlusSpec(e){
      if(!this.properties.goods.count){
        this.setData({
          'goods.count': ''
        })
      }
      // 焦点放输入框
      this.setData({
        focusOnDecimalInputComponent: true
      })
    },

    handlePlus(e){
      this.setData({
        'quantity': this.properties.quantity+1,
      })
      this._triggleRefreshGoodCount(this.properties.quantity);
    },
    
    handleMinus(e){
      if(this.properties.quantity === 0){
        return;
      }
      this.setData({
        'quantity': this.properties.quantity - 1,
      })
      this._triggleRefreshGoodCount(this.properties.quantity);
    },
  
    clickHandle() {
      this.triggerEvent('click', {
        goods: this.data.goods
      });
    },

    clickThumbHandle() {
      this.triggerEvent('thumb', {
        goods: this.data.goods
      });
    },

    addCartHandle(e) {
      const {
        id
      } = e.currentTarget;
      const {
        id: cardID
      } = e.currentTarget.dataset;
      this.triggerEvent('add-cart', {
        ...e.detail,
        id,
        cardID,
        goods: this.data.goods,
      });
    },

    genIndependentID(id) {
      let independentID;
      if (id) {
        independentID = id;
      } else {
        independentID = `goods-card-${~~(Math.random() * 10 ** 8)}`;
      }
      this.setData({
        independentID
      });
    },

    init() {
      const {
        thresholds,
        id
      } = this.properties;
      this.genIndependentID(id);
      if (thresholds && thresholds.length) {
        this.createIntersectionObserverHandle();
      }
    },

    clear() {
      this.clearIntersectionObserverHandle();
    },

    intersectionObserverContext: null,

    createIntersectionObserverHandle() {
      if (this.intersectionObserverContext || !this.data.independentID) {
        return;
      }
      this.intersectionObserverContext = this.createIntersectionObserver({
        thresholds: this.properties.thresholds,
      }).relativeToViewport();

      this.intersectionObserverContext.observe(
        `#${this.data.independentID}`,
        (res) => {
          this.intersectionObserverCB(res);
        },
      );
    },

    intersectionObserverCB() {
      this.triggerEvent('ob', {
        goods: this.data.goods,
        context: this.intersectionObserverContext,
      });
    },

    clearIntersectionObserverHandle() {
      if (this.intersectionObserverContext) {
        try {
          this.intersectionObserverContext.disconnect();
        } catch (e) {}
        this.intersectionObserverContext = null;
      }
    },
  },
});
